package fr.umlv.favorites;

import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumnModel;

import kiyut.ekspos.BrowserWindow;

import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.ObjectId;
import org.apache.chemistry.opencmis.commons.enums.BaseTypeId;
import org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException;

import fr.umlv.authentication.SessionHandler;
import fr.umlv.cmis.gedconfig.Shortcut;
import fr.umlv.cmis.gedconfig.XMLAccess;
import fr.umlv.cmis.gedconfig.XMLNameNotFoundException;
import fr.umlv.model.ClientModel;

// TODO: Auto-generated Javadoc
/**
 * The Class BookmarkView.
 */
@SuppressWarnings("serial")
public class BookmarkView extends JPanel implements TableModelListener{

	/** The bundle. */
	private ResourceBundle bundle = ResourceBundle.getBundle("kiyut.ekspos.BrowserWindow", SessionHandler.getLocale());
	
	/** The t favorite. */
	private final JTable tFavorite;
	
	/** The map bookmark. */
	private HashMap<String, Shortcut> mapBookmark;
	
	/** The model fav. */
	private final DataFavoriteTableModel modelFav;
	
	/** The instance. */
	private static BookmarkView instance = null;

	/**
	 * Gets the single instance of BookmarkView.
	 *
	 * @return single instance of BookmarkView
	 */
	public static BookmarkView getInstance() {
		if(instance==null)
			instance = new BookmarkView();
		return instance;
	}

	/**
	 * Instantiates a new bookmark view.
	 */
	private BookmarkView() {

		setLayout(new GridLayout());

		mapBookmark = XMLAccess.getInstance().getBookmarks();

		List<String> keys = new ArrayList<String>();
		for (Map.Entry<String, Shortcut> e : mapBookmark.entrySet()) {
			keys.add(e.getKey());
		}

		modelFav = new DataFavoriteTableModel(mapBookmark.size(), 3, keys);
		
		modelFav.addTableModelListener(this);
		
		tFavorite = new JTable(modelFav);
		tFavorite.setDefaultRenderer(JButton.class, new DefaultTableCellRenderer() {
			@Override
			public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {

				JButton actualButton = (JButton) value;

				actualButton.setForeground(Color.black);
				actualButton.setFocusPainted(false);
				actualButton.setBorderPainted(false);
				actualButton.setContentAreaFilled(false);

				if (col == 0) {
					table.getColumnModel().getColumn(col).setPreferredWidth(140);
					actualButton.setHorizontalAlignment(SwingConstants.LEFT);


				}
				if (col == 1) {
					table.getColumnModel().getColumn(col).setMaxWidth(20);
				}

				if (col == 2) {
					table.getColumnModel().getColumn(col).setMaxWidth(20);
				}


				return actualButton;
			}
		});

		add(tFavorite);
	}

	/**
	 * Inits the.
	 */
	public void init() {

		tFavorite.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {

				TableColumnModel columnModel = tFavorite.getColumnModel();
				int column = columnModel.getColumnIndexAtX(e.getX());
				int row = e.getY() / tFavorite.getRowHeight();
				Object value;

				if (row >= tFavorite.getRowCount() || row < 0 || column >= tFavorite.getColumnCount() || column < 0)
					return;

				value = tFavorite.getValueAt(row, column);

				String key = ((JButton) tFavorite.getValueAt(row, 0)).getText();

				if ((value instanceof JButton)) {
					if (column == 2) {
						try {

							XMLAccess.getInstance().delBookmark(key);
							modelFav.remove(tFavorite.getSelectedRow());
							tFavorite.revalidate();
						} catch (XMLNameNotFoundException e1) {
							JOptionPane.setDefaultLocale(SessionHandler.getLocale());
							JOptionPane.showMessageDialog(BrowserWindow.getInstance(), bundle.getString("ErrorConsult.text"), "Error", JOptionPane.ERROR_MESSAGE);
						}
					}  else{

						CmisObject cmisDoc = null;

						try {

							ObjectId objID = SessionHandler.getClientSession().getSession().createObjectId(mapBookmark.get(key).getId());
							cmisDoc = SessionHandler.getClientSession().getSession().getObject(objID);

							if (column == 0) {

								try {
									ClientModel.openCmisObject(cmisDoc);
								} catch (CmisObjectNotFoundException e1) {
									JOptionPane.showMessageDialog(BrowserWindow.getInstance(), bundle.getString("OpenExist.text"), "Error", JOptionPane.ERROR_MESSAGE);
									return;
								} catch (IOException e2) {
									JOptionPane.showMessageDialog(BrowserWindow.getInstance(), bundle.getString("OpenExist.text"), "Error", JOptionPane.ERROR_MESSAGE);
									return;
								}
							}

							if (column == 1) {
								if (BaseTypeId.CMIS_DOCUMENT.equals(cmisDoc.getBaseTypeId())) {
									BrowserWindow.getInstance().updateLocationModel(((Document) cmisDoc).getParents().get(0));
								} else
									BrowserWindow.getInstance().updateLocationModel(cmisDoc);
							}

						} catch (CmisObjectNotFoundException e1) {
							JOptionPane.setDefaultLocale(SessionHandler.getLocale());
							JOptionPane.showMessageDialog(BrowserWindow.getInstance(), bundle.getString("OpenExist.text"), "Error", JOptionPane.ERROR_MESSAGE);
							return;
						}
					} 
				}
			}
		});

	}

	/**
	 * Insert.
	 *
	 * @param bookmark the bookmark
	 */
	public void insert(String bookmark) {
		mapBookmark = XMLAccess.getInstance().getBookmarks();
		modelFav.insert(bookmark);
	}

	/* (non-Javadoc)
	 * @see javax.swing.event.TableModelListener#tableChanged(javax.swing.event.TableModelEvent)
	 */
	@Override
	public void tableChanged(TableModelEvent e) {
		tFavorite.revalidate();
		tFavorite.repaint();
	}

}
